#!/usr/bin/env python

import config
import datastore
import json

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

class QuerySpotsInBoundPage(webapp.RequestHandler):
    def _error(self, msg):
        self.response.out.write(json.dumps({'msg': msg}))

    def get(self):
        try:
            # Get the latitude and longitude fields
            ne_lat = self.request.get('ne_lat')
            ne_lon = self.request.get('ne_lon')
            sw_lat = self.request.get('sw_lat')
            sw_lon = self.request.get('sw_lon')

            # Check the availability
            if ne_lat == '' or ne_lon == '' or sw_lat == '' or sw_lon == '':
                raise ValueError('latitude or longitude is empty')

            # Cast latitude and longitude from string to float
            ne_lat = float(ne_lat)
            ne_lon = float(ne_lon)
            sw_lat = float(sw_lat)
            sw_lon = float(sw_lon)

            # Check consistency
            if ne_lat < sw_lat:
                raise ValueError('incorrect latitude order')

        except ValueError as e:
            self._error('invalid latitude or longitude: ' + str(e))
            return


        spots = []
        rows = datastore.HotSpot.get_in_bound(ne_lat, ne_lon, sw_lat, sw_lon)

        for row in rows:
            spots.append({
                'key': str(row.key()),
                'name': row.name,
                'lat': row.location.lat,
                'lon': row.location.lon
            })

        self.response.out.write(json.dumps({'spots': spots}))
